<template>
  <el-table
    ref="multipleTable"
    v-loading="loading"
    :data="tableData"
    :row-style="rowClass"
    style="width: 100%;"
    stripe
    class="table-list"
    :class="tableClassName"
    @selection-change="handleSelectionChange"
    @row-click="rowChecked"
  >
    <slot name="column" />
  </el-table>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'SkTable',
  props: {
    multipleSelection: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array,
      default: () => []
    },
    single: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    pageSize: {
      type: Number,
      default: 20
    }
  },
  data() {
    return {
      selectRow: [] // 高亮样式
    }
  },
  computed: {
    ...mapState({ needTagsView: state => state.settings.tagsView }),
    tableClassName() {
      return this.needTagsView ? 'el-body-page-roll-tag' : 'el-body-page-roll'
    }
  },
  watch: {
    tableData(arr) {
      if (Array.isArray(arr)) {
        // this.addTaleData()
      }
    }
  },
  methods: {
    // list表格填充空白行
    addTaleData() {
      if (this.tableData.length < this.pageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    /* 表格行选中事件 start */
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach((item) => {
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }

      // 修改按钮禁用状态
      this.$emit('update:single', val.length !== 1)

      this.selectRow = []
      // 获取选中行
      this.$emit('update:multipleSelection', val)
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    }
  }
}
</script>

